<template>
    <div>
        <el-form label-width="110px" size="small">
            <el-row class="form-row">
                <el-col :span="12">
                    <el-form-item label="产品代码:" v-if="isBatchStock">
                        <RiskEntryInput @set-entry-data="getEntryslist" :returnDatas="instructionCache.fundCode" />
                    </el-form-item>
                    <el-form-item label="组合编码:" v-if="isBatchStock">
                        <el-select v-model="instructionCache.fundAccountCode" size="mini" @change="handleFundAccountCodeChange">
                            <el-option
                                v-for="i in computedFundAccountCodeSelectData"
                                :key="i.fundAccountCode"
                                :label="i.fundAccountCode + ' ' + i.fundAccountName"
                                :value="i.fundAccountCode"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="业务类型:">
                        <el-select disabled size="mini" v-model="instructionCache.businClass">
                            <el-option label="B 存款类" value="B"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="委托方向:" v-if="isBatchFund">
                        <el-select
                            v-model="instructionCache.orderDirection"
                            size="mini"
                            disabled
                            :class="['font-color-' + textColor]"
                            @change="handleChange('orderDirection')"
                        >
                            <el-option label="存款支取" value="i"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="委托方向:" v-if="isBatchStock">
                        <el-select
                            v-model="instructionCache.orderDirection"
                            size="mini"
                            disabled
                            :class="['font-color-' + textColor]"
                            @change="handleChange('orderDirection')"
                        >
                            <el-option label="存款支取" value="i"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="支取类型:">
                        <el-select size="mini" v-model="instructionCache.advanceType" @change="handleChange('advanceType')">
                            <el-option v-for="i in withDrawSelectData" :key="i.dictKey" :label="i.dictKeyName" :value="i.dictKey"> </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="支取日期:"
                        ><el-date-picker
                            v-model="instructionCache.drawDate"
                            type="date"
                            format="yyyy/MM/dd"
                            value-format="yyyyMMdd"
                            placeholder="请选择"
                            style="width: 100%"
                            :picker-options="pickerOptions"
                            @change="handleChange('drawDate')"
                        ></el-date-picker
                    ></el-form-item>
                </el-col>
            </el-row>
        </el-form>
    </div>
</template>
<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import { SGU_CACHE } from '@/utils/diction-const-util';
import moment from 'moment';
import RiskEntryInput from '@/common/components/risk-entry-input.vue';
import RiskInputNumber from '@/pages/risk-measure/components/risk-input-number.vue';

// 存款支取指令风险下单Tab
export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
}
@Component({
    name: 'DepositPaidForm',
    components: {
        RiskEntryInput,
        RiskInputNumber,
    },
})
export default class DepositPaidForm extends Vue {
    @Prop()
    detail: any;
    @Prop()
    renderCount: number;
    @Prop()
    selectStockInfo: any;
    @Prop()
    isBatchFund: boolean; // 多基金指令
    @Prop()
    isBatchStock: boolean; // 多基金指令

    instructionCache: any = {
        fundCode: '',
        receiptNo: '', // 存单号
        fundAccountCode: '',
        fundAccountName: '',
        drawInterest: '', // 利息金额
        advanceType: '1', // 支取类型
        orderBalance: '', // 兑付金额
        businClass: 'B',
        drawDate: '', // 支取日期
        orderDirection: 'i', // 委托方向
    };

    withDrawSelectData: any[] = [
        { dictKeyName: '提前兑付', dictKey: '1' },
        { dictKeyName: '通知兑付', dictKey: '2' },
        { dictKeyName: '解约', dictKey: '3' },
        { dictKeyName: '到期兑付', dictKey: '4' },
    ]; // 支取类型下拉数据

    pickerOptions: any = {};
    stockInfo: any = {}; // 证券信息
    fundAccountCodeSelectData: any[] = [];
    fundCodeSelectData: any[] = []; // 产品序号下拉框数据
    receiptNoData: any[] = []; // 存单号数据
    currentTradeDay: number = 0;
    textColor: string = 'green';
    stockReport: any[] = []; // 证券代码下拉框数据

    prohFundCode: boolean = false;

    @Watch('detail', { immediate: true, deep: true })
    async onWatchDetail() {
        if (this.detail && Object.keys(this.detail).length) {
            let instruction: any = {};
            for (const key in this.detail) {
                instruction[key] = this.detail[key];
            }
            // 存款期限
            if (instruction.depositType != '2' && instruction.mutureType == '1' && !instruction.depositLimitTime) {
                instruction.depositLimitTime = String(moment(instruction.mutureDate).diff(moment(instruction.depositStartDate), 'months'));
            }
            instruction.mutureType = instruction.mutureType || '1';
            instruction.businClass = instruction.businessType;
            this.instructionCache = JSON.parse(JSON.stringify(instruction));
            await this.getCurrentTradeDay();
        }
    }

    // @Watch('renderCount', { immediate: true, deep: true })
    // async onWatchPaidDetail(newValue, oldValue) {
    //     if (JSON.stringify(this.paidDetail) !== JSON.stringify(this.instructionCache)) {
    //         if (this.paidDetail && this.paidDetail.orderDirection == 'i') {
    //             await this.getCurrentTradeDay();
    //             // 获取组合编码下拉框数据
    //             let arr = await SGU_CACHE('FundAccount', '/fundInfo/accounts', []);
    //             arr.forEach(item => {
    //                 this.fundAccountCodeSelectData[item.fundCode] = item.fundAccounts;
    //             });
    //             let instruction = this.paidDetail;
    //             this.prohFundCode = true;
    //             for (const key in instruction) {
    //                 if (key == 'drawDate') {
    //                     this.instructionCache.drawDate = this.paidDetail.drawDate || this.instructionCache.drawDate;
    //                 } else {
    //                     this.instructionCache[key] = this.paidDetail[key];
    //                 }
    //             }
    //             await this.getFundPositionList();
    //             this.instructionCache.advanceType = this.paidDetail.advanceType || '1';
    //             this.instructionCache.businClass = 'B';
    //             await this.getstockCodeList(instruction.reportCode);
    //             this.stockInfo = this.stockReport.find(
    //                 item => item.reportCode === { '1': '870870', '2': '860860', '3': '890890' }[this.paidDetail.depositType]
    //             );
    //             this.$emit('getStockInfo', this.stockInfo, '5');
    //         }
    //     } else {
    //         this.instructionCache = {
    //             fundCode: '',
    //             receiptNo: '', // 存单号
    //             fundAccountCode: '',
    //             fundAccountName: '',
    //             drawInterest: '', // 利息金额
    //             advanceType: '1', // 支取类型
    //             orderBalance: '', // 兑付金额
    //             businClass: 'B',
    //             drawDate: '', // 支取日期
    //             orderDirection: 'i', // 委托方向
    //         };
    //     }
    // }

    @Watch('selectStockInfo', { immediate: true, deep: true })
    onWatchStockInfo() {
        if (this.selectStockInfo) {
            this.stockInfo = this.selectStockInfo;
            this.getCurrentTradeDay();
            // this.orderDirectionSelectData = this.stockInfoCache.tradeDirections;
            // this.getStockCodeList(this.stockInfo.reportCode);
        }
    }

    async created() {
        // 获取产品信息 (产品序号下拉框数据)
        this.fundCodeSelectData = await SGU_CACHE('FundInfo', '/fundInfo/list', []);

        // 获取组合编码下拉框数据
        let arr = await SGU_CACHE('FundAccount', '/fundInfo/accounts', []);
        arr.forEach(item => {
            this.fundAccountCodeSelectData[item.fundCode] = item.fundAccounts;
        });
        this.getCurrentTradeDay();
    }

    // 产品代码回调
    getEntryslist(val: any) {
        if (this.instructionCache.fundCode != val) {
            this.prohFundCode = false;
            this.instructionCache.fundCode = val;
            this.handleFundCodeChange(val);
        }
    }

    handleChange(param) {
        if (param == 'orderDirection') {
            this.instructionCache = {
                fundCode: this.instructionCache.fundCode,
                fundNameSt: this.instructionCache.fundNameSt,
                fundAccountCode: this.instructionCache.fundAccountCode,
                fundAccountName: this.instructionCache.fundAccountName,
                orderDirection: 'F',
            };
        }
        this.instructionCache.instructionTypeName = '存款类';
        this.$emit('handleSettingValue', this.instructionCache, '5');
    }

    get computedFundAccountCodeSelectData(): any {
        return this.fundAccountCodeSelectData[this.instructionCache.fundCode];
    }

    async handleFundCodeChange(val: string) {
        let fund = this.fundCodeSelectData.find(item => item.fundCode === val) || {};
        let fundAccount = (this.fundAccountCodeSelectData[this.instructionCache.fundCode] || [])[0] || {};
        this.instructionCache.fundAccountCode = fundAccount.fundAccountCode;
        if (this.prohFundCode) {
            this.prohFundCode = false;
            return;
        }
        await this.getFundPositionList();
        this.prohFundCode = false;
        this.handleSelect(this.instructionCache.receiptNo);
    }

    // 获取证券代码下拉框数据
    async getstockCodeList(value: string) {
        await this.$axios
            .post('/dict/stock/report/select/' + 6, {
                dictKey: value,
                dictKeyName: value,
            })
            .then((res: any) => {
                this.stockReport = res || [];
            });
    }

    // 组合编码变化
    handleFundAccountCodeChange(value: string): void {
        let fundAccount =
            (this.computedFundAccountCodeSelectData[this.instructionCache.fundCode] || []).find(item => item.fundAccountCode === value) || {};

        this.instructionCache.fundAccountName = fundAccount.fundAccountName;
        this.handleChange('fundAccountCode');
    }

    // 选中可支取存单事件
    handleSelect(receiptNo: any) {
        let disabled: boolean = false;
        for (let index = 0; index < this.receiptNoData.length; index++) {
            if (this.receiptNoData[index].receiptNo == receiptNo && this.receiptNoData[index].isGivenOrder) {
                this.yh_message_warn('当日已支取过，不可重复支取！');
                this.instructionCache.receiptNo = '';
                disabled = true;
                break;
            }
        }
        if (disabled) {
            return;
        }
        let row = this.receiptNoData.find(item => item.receiptNo == receiptNo) || {};
        this.instructionCache.reportCode = row.reportCode;
        // this.instructionCache.receiptNo = row.receiptNo; // 存单号
        this.instructionCache.depositRate = row.rate;
        // this.instructionCache.depositStartDate = row.beginDate;
        this.instructionCache.mutureDate = row.endDate;
        // this.instructionCache.drawInterest = row.receivableInterest;
        this.instructionCache.orderBalance = row.balance;
        this.instructionCache.expireBalance = Number(row.receivableInterest) + Number(row.balance);
        this.instructionCache.bankCode = row.bankNo;
        this.instructionCache.advanceLimitFlag = row.advanceLimitFlag;
        this.instructionCache.receivableInterest = row.receivableInterest; //
        this.instructionCache.balance = row.balance;
        this.instructionCache.confirmNo = row.confirmNo;
        this.instructionCache.depositType = row.depositType;
        this.instructionCache.drawInterest = row.receivableInterest;
        this.instructionCache.depositStartDate = row.beginDate;
        this.stockInfo = this.stockReport.find(
            item => item.reportCode === { '1': '870870', '2': '860860', '3': '890890', '6': '880880' }[row.depositType]
        );
        this.$emit('getStockInfo', this.stockInfo);
        this.handleChange('receiptNo');
    }

    // 获取当前交易日期
    getCurrentTradeDay() {
        return new Promise((resolve, reject) => {
            this.$axios
                .get('/dict/initTradeDate')
                .then((res: any) => {
                    this.currentTradeDay = res;
                    this.instructionCache.drawDate = this.currentTradeDay.toString();
                    let date = new Date(moment(this.currentTradeDay.toString()).format('YYYY-MM-DD')).getTime();
                    this.pickerOptions = {
                        disabledDate(time) {
                            return time.getTime() < date - 1 * 24 * 3600 * 1000;
                        },
                    };
                    resolve(res);
                })
                .catch(err => {
                    reject(err);
                });
        });
    }

    // 利息金额、兑付金额
    getInputNumber(args: any) {
        let value = args[0];
        let field = args[1];
        this.instructionCache[field] = value;
        this.handleChange(args[1]);
    }

    // 可支取存单信息分页
    getFundPositionList() {
        return new Promise((resolve, reject) => {
            this.$axios
                .post('/position/bankDeposit/operationalReceipt/select', { fundCode: [this.instructionCache.fundCode] })
                .then((res: any) => {
                    res.forEach(ele => {
                        ele.totalBalance = Number(ele.balance || '0') + Number(ele.receivableInterest || '0');
                    });
                    this.receiptNoData = res;
                    if (res.length < 1) {
                        this.instructionCache.receiptNo = '';
                    }
                    resolve(res);
                })
                .catch(err => {
                    reject(err);
                });
        });
    }
}
</script>
<style lang="scss" scoped>
@import '@/pages/risk-measure/style/measure';

.font-color-green {
    /deep/ input {
        color: green !important;
    }
    /deep/ .el-input-group__append {
        color: green !important;
    }
}
</style>
